package com.egg.basic.controller.feign;


import com.egg.basic.enums.pay.ClientTypeEnum;
import com.egg.basic.enums.pay.PayTypeEnum;
import com.egg.basic.fegin.BasicPayFeignClient;
import com.egg.basic.model.request.PayPost;
import com.egg.basic.model.request.RefundPost;
import com.egg.basic.service.pay.IPayRecordService;
import com.egg.basic.service.pay.IRefundRecordService;
import com.egg.common.core.exception.CustomException;
import com.egg.common.core.model.controller.FeignController;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.util.OptionalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * <p>
 * 支付记录 前端控制器
 * </p>
 *
 * @author east
 * @since 2021-11-26
 */
@Slf4j
@Api(tags = FeignController.API_PREFIX + "支付中心")
@RestController
public class FeignPayController extends FeignController implements BasicPayFeignClient {


    @Autowired
    private IPayRecordService payRecordService;
    @Autowired
    private IRefundRecordService refundRecordService;


    @Override
    @ApiOperation(value = "支付")
    @PostMapping("/pay")
    public ResponseData<String> pay(@RequestBody PayPost param) {
        Optional<PayTypeEnum> payAndRefundType = PayTypeEnum.findByCode(param.getPayType());
        if (!payAndRefundType.isPresent()) {
            throw new CustomException("支付类型不支持");
        }
        Optional<ClientTypeEnum> clientType = ClientTypeEnum.findByCode(param.getClientType());
        if (!clientType.isPresent()) {
            throw new CustomException("支付端不支持");
        }
        String url = payRecordService.add(
                payAndRefundType.get()
                , clientType.get()
                , param.getBusinessType()
                , param.getBusinessId()
                , OptionalUtil.build(param.getUserId())
                , param.getAmount()
                , param.getSubject()
        );
        return ResponseData.success(url);
    }

    @Override
    @ApiOperation(value = "退款")
    @PostMapping("/refund")
    public ResponseData<String> refund(@RequestBody RefundPost param) {
        return refundRecordService.add(param.getBusinessType(), param.getBusinessId(), param.getRemark());
    }


}

